//
//  ST_BTChatInputBar.swift
//  btvideo
//
//  Created by mac on 2020/6/30.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyUserDefaults
import SwifterSwift
import SwiftyJSON
import MobileCoreServices
import AVFoundation
import Photos
import ISEmojiView
import TZImagePickerController

class ST_BTChatInputBar: UIView {
    
    static let input_height = (10+36+10).cgFloat
    
    static let normal_height:CGFloat = 122 + BTSafeAreaBottom
    
    static var is_shared_emoji = true
    
    var uploadType : UploadType = .unknow
    private lazy var picture_images = [UIImage]()
    private  var last_select_assets  = [PHAsset]()
    
    
    weak var vc:ST_PrivateChatViewController?
    
    //视频云地址
    var network_video_url = ""

    
    
    //    MARK: - Closure
    var start_lauch_emoji_closure:((CGRect,ChatEmojiCellModel)->())?
    
    var stop_lauch_emoji_closure:(()->())?
    
    var did_select_emoji_closure:((CGRect,ChatEmojiCellModel)->())?
    
    //    缩略图本地路径  原图本地路径
    var send_image_closure:((String,String,CGSize,Bool)->())?
    
    //    缩略图本地路径  原图本地路径
    var Closure:((String,String,CGSize)->())?
     // 礼物 🎁
    var present_goods_closure:(()->())?
    //发送红包
    var send_red_packet_closure:((Float,String)->())?
    // 邀请真人认证
    var require_detect_closure:(()->())?
//
    var send_emoji_closure:((BTEmojiItemModel)->())?
    
    var send_text_closure:((String)->())?
    
    var request_media_talk_closure:(()->())?
    
    var ask_wechat_closure:(()->())?
//     缩略图路径 尺寸 本地路径
    var send_video_closure:((String,CGSize,String)->())?
//    更改高度状态的回调
    var modify_height_status:(()->())?
    
    /**
     对方只支持 文字聊天
     */
    var onlyText = false
    
    
    
//    录制需要外部UI 参与 提供delegate 而不是 Closure
    weak var recordAudioDelegate:DPChatToolBarAudioDelegate?{
        didSet{
            if let delegate = recordAudioDelegate{
                self.speaker_btn.delegate = delegate
            }
        }
    }
//    MARK: - public
    var heightStatus:ST_DTInputBarHeightStatus = .normal {
        didSet{
            
            
            self.inputTextView.isHidden = self.heightStatus == .speaker
            
            self.speaker_btn.isHidden = self.heightStatus != .speaker
            
            self.voice_btn.isSelected = self.heightStatus == .speaker
           
        }
    }
//    MARK: - init
    /// 跟客服MM 聊天
    let is_chat_to_assistant:Bool
    
    init(frame: CGRect,is_chat_to_assistant:Bool){
    
        self.is_chat_to_assistant = is_chat_to_assistant
        
        super.init(frame: frame)
        
        self.backgroundColor = Color.white
        
        let top_view = UIView()
        top_view.backgroundColor = Color.white
        self.addSubview(top_view)
        self.addSubview(line)
        
        top_view.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(self)
            make.height.equalTo(ST_BTChatInputBar.input_height)
        }
        
        line.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(self)
            make.height.equalTo(1)
        }
        
        top_view.addSubview(voice_btn)
        voice_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(32)
        }
        
        var topRightBtn = gift_btn
        
        if Defaults[.isPanda] || is_chat_to_assistant {
            
            topRightBtn = top_send_btn
            top_view.addSubview(top_send_btn)
            top_send_btn.snp.makeConstraints { (make) in
                make.right.equalToSuperview().offset(-15)
                make.centerY.equalToSuperview()
                make.height.equalTo(32)
                make.width.equalTo(66)
            }
            
        }else{
            
            top_view.addSubview(gift_btn)
            gift_btn.snp.makeConstraints { (make) in
                make.right.equalToSuperview().offset(-15)
                make.centerY.equalToSuperview()
                make.width.height.equalTo(32)
            }
            
        }
        
        top_view.addSubview(input_status_control_btn)
        input_status_control_btn.snp.makeConstraints { (make) in
            make.right.equalTo(topRightBtn.snp.left).offset(-10)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(32)
        }
        
        top_view.addSubview(inputTextView)
        inputTextView.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(voice_btn.snp.right).offset(10)
            make.right.equalTo(input_status_control_btn.snp.left).offset(-10)
            make.height.equalTo(36)
        }
        
        
        
        self.addSubview(speaker_btn)
        speaker_btn.isHidden = true
        speaker_btn.snp.makeConstraints { (make) in
            
            make.left.right.bottom.top.equalTo(inputTextView)
        }
        
        
        self.addSubview(bottom_root_view)
        bottom_root_view.snp.makeConstraints { (make) in
            make.left.right.equalTo(self)
            make.top.equalTo(top_view.snp.bottom)
            make.height.equalTo(ST_BTChatInputBar.normal_height - ST_BTChatInputBar.input_height)
        }
        
        let offset = TIANCompatibleValue(value: 26)
        
        var btnCollection = [UIControl]()
        
        if is_chat_to_assistant{
            
            btnCollection = [pick_picture_btn]
            
        }else if Defaults[.isPanda] {
            
            btnCollection = [emoji_talk_btn,pick_picture_btn,snap_chat_btn,gift_talk_btn]
             
        }else{
            
            var center_btn:UIControl = snap_chat_btn
            var centerLeftBtn:UIControl = take_picture_btn
            
            if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male{
                center_btn = wechat_btn
                centerLeftBtn = snap_chat_btn
            }
//            redPacketBtn 删除红包
            btnCollection = [center_btn,centerLeftBtn,pick_picture_btn,media_talk_btn]
        }
        
        
        btnCollection.forEach({ bottom_root_view.addSubview($0) })
        
        bottom_root_view.addSubview(bottom_forbid_btn)
        bottom_forbid_btn.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        switch btnCollection.count {
            
        case 1:
            
            btnCollection[0].snp.makeConstraints { (make) in
                make.height.equalTo(30+20)
                make.width.equalTo(48)
                make.top.equalToSuperview().offset(5)
                make.left.equalToSuperview().offset(50)
            }
            
        case 2:
            
            
            btnCollection[0].snp.makeConstraints { (make) in
                make.height.equalTo(30+20)
                make.width.equalTo(48)
                make.right.equalTo(bottom_root_view.snp.centerX).offset(-20)
                make.top.equalToSuperview().offset(5)
            }
            
            
            btnCollection[1].snp.makeConstraints { (make) in
                make.height.width.top.equalTo(btnCollection[0])
                make.left.equalTo(bottom_root_view.snp.centerX).offset(20)
                make.top.equalToSuperview().offset(5)
            }
            
        case 3:
            
            let threeOffset = TIANCompatibleValue(value: 80)
            
            
            btnCollection[1].snp.makeConstraints { (make) in
                make.height.equalTo(30+20)
                make.width.equalTo(48)
                make.top.equalToSuperview().offset(5)
                make.centerX.equalToSuperview()
            }
            
            
            btnCollection[2].snp.makeConstraints { (make) in
                make.height.width.top.equalTo(btnCollection[1])
                make.left.equalTo(btnCollection[1].snp.right).offset(threeOffset)
            }
            
            
            
            btnCollection[0].snp.makeConstraints { (make) in
                make.height.width.top.equalTo(btnCollection[1])
                make.right.equalTo(btnCollection[1].snp.left).offset(-threeOffset)
            }
            
        case 4:
            
            let fourOffset = TIANCompatibleValue(value: 20)
            
            btnCollection[1].snp.makeConstraints { (make) in
                make.height.equalTo(30+20)
                make.width.equalTo(48)
                make.top.equalToSuperview().offset(5)
                make.centerX.equalToSuperview().offset(-48/2.0-fourOffset)
            }
            
            btnCollection[2].snp.makeConstraints { (make) in
                make.height.width.top.equalTo(btnCollection[1])
                make.left.equalTo(btnCollection[1].snp.right).offset(2*fourOffset)
            }
            
            btnCollection[0].snp.makeConstraints { (make) in
                make.height.width.top.equalTo(btnCollection[2])
                make.right.equalTo(btnCollection[1].snp.left).offset(-2*fourOffset)
            }
            
            btnCollection[3].snp.makeConstraints { (make) in
                make.height.width.top.equalTo(btnCollection[2])
                make.left.equalTo(btnCollection[2].snp.right).offset(2*fourOffset)
            }
            
        case 5:
            
            
            
            btnCollection[2].snp.makeConstraints { (make) in
                make.height.equalTo(30+20)
                make.width.equalTo(48)
                make.top.equalToSuperview().offset(5)
                make.centerX.equalToSuperview()
            }
            
            
            btnCollection[3].snp.makeConstraints { (make) in
                make.height.width.top.equalTo(btnCollection[2])
                make.left.equalTo(btnCollection[2].snp.right).offset(offset)
            }
            
            
            
            btnCollection[1].snp.makeConstraints { (make) in
                make.height.width.top.equalTo(btnCollection[2])
                make.right.equalTo(btnCollection[2].snp.left).offset(-offset)
            }
            
            
            
            btnCollection[0].snp.makeConstraints { (make) in
                make.height.equalTo(30+20)
                make.width.equalTo(48)
                make.top.equalToSuperview().offset(5)
                make.right.equalTo(btnCollection[1].snp.left).offset(-offset)
            }
            
            
            
            btnCollection[4].snp.makeConstraints { (make) in
                make.height.width.top.equalTo(btnCollection[2])
                make.left.equalTo(btnCollection[3].snp.right).offset(offset)
            }
            
        default:
            break
        }
        
        
        
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//    MARK: - Properties
    
    
    fileprivate lazy var line:UIView = {
        let control = UIView()
        control.backgroundColor = Color.init(hex: 0xF2F4F7)
        return control
    }()
    
    fileprivate lazy var voice_btn:UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setImageForAllStates(ST_ImageUtils.imageName("mycenter_icon_语音输入")!)
        
        btn.setImage(ST_ImageUtils.imageName("mycenter_icon_键盘")!, for: UIControl.State.selected)
        
        btn.addTarget(self, action: #selector(audio_record_hanlde(sender:)), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    fileprivate lazy var gift_btn:UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setImageForAllStates(ST_ImageUtils.imageName("chat_gift_icon")!)
        btn.addTarget(self, action: #selector(present_gift_handle), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    
    fileprivate lazy var top_send_btn:UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setTitleForAllStates("发送")
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium)
        btn.backgroundColor = UIColor(hex: 0xFEC207)
        btn.cornerRadius = 32/2.0
        btn.addTarget(self, action: #selector(send_text_handle), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    lazy var input_status_control_btn:UIButton = {
        
        let btn = UIButton.init(type: .custom)
        
        btn.setImageForAllStates(ST_ImageUtils.imageName("消息_inputBar_输入_normal")!)
        
        btn.setImage(ST_ImageUtils.imageName("消息_inputBar_输入_selected")!, for: UIControl.State.selected)
        
        btn.addTarget(self, action: #selector(show_emoji_view), for: UIControl.Event.touchUpInside)
        
        return btn
    }()
    
    let input_text_color = Color.init(hex: 0x00527F)!
    
    let input_placeholder_text_color = Color.init(hex: 0x999999)!
    
    var input_placeholder_text = ""{
        didSet{
            if inputTextView.text.isEmpty {
                inputTextView.text = input_placeholder_text
                inputTextView.textColor = input_placeholder_text_color
            }
        }
    }
    
    fileprivate lazy var inputTextView:UITextView = {
        let control = UITextView.init(frame: CGRect.zero)
        control.backgroundColor = Color.init(hexString: "#F2F4F7")
        control.cornerRadius = 6
        control.tintColor = Color.init(hex:  0xcccccc)!
        control.textColor = input_placeholder_text_color
        control.font = DTChatTextFont
        control.returnKeyType = .send
        control.enablesReturnKeyAutomatically  = true
        control.inputAccessoryView = UIView()
        control.delegate = self
        control.showsVerticalScrollIndicator = false
       return control
    }()
    
    fileprivate lazy var change_to_input_text_control:UIControl = {
        
        let control = UIControl()
        
        control.addTarget(self, action: #selector(show_emoji_view), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    fileprivate lazy var emojiView:ST_BTCustomEmojiView = {
        
        let control = ST_BTCustomEmojiView.init(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ST_BTCustomEmojiView.height))
        
        control.selected_closure = {[weak self] emoji in
            
            self?.send_emoji_closure?(emoji)
            
        }
        
        return control
    }()
    
    
    
    
    fileprivate lazy var speaker_btn:ST_ChatToolBarAudioButton = {
       let control = ST_ChatToolBarAudioButton()
        control.backgroundColor = Color.init(hexString: "#F2F4F7")!
        control.cornerRadius = 20
        return control
    }()
    
    
    
    fileprivate lazy var bottom_root_view:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
        return control
    }()
    
    /// 一个限制事件隐藏btn
    fileprivate lazy var bottom_forbid_btn:UIButton = {
        let btn = UIButton.init(type: UIButton.ButtonType.custom)
        btn.backgroundColor = .clear
        /// 女性未认证真人
        if let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo,user.sex == .female,FACE_AVATAE_STATE != 3{
            btn.isHidden = false
        }else{
            btn.isHidden = true
        }
        //btn.cornerRadius = 0
        //btn.semanticContentAttribute = .forceRightToLeft
        btn.addTarget(self, action: #selector(face_status_confined_handle), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    fileprivate lazy var pick_picture_btn:ST_VerticalButton = {
        
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 9, bottom: 20, right: 9)
        control.title_bottom_offset = 0
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        let attrString = NSMutableAttributedString(string: "照片")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 12),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.setTitle(attrString, for: UIControl.State.normal)
        control.setImageForAllStates(ST_ImageUtils.imageName("n_私信_icon_发送图片")!)
        control.addTarget(self, action: #selector(select_picture_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var take_picture_btn:ST_VerticalButton = {
        
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 9, bottom: 20, right: 9)
        control.title_bottom_offset = 0
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        let attrString = NSMutableAttributedString(string: "拍摄")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 12),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.setTitle(attrString, for: UIControl.State.normal)
        control.setImageForAllStates(ST_ImageUtils.imageName("n_私信_icon_录制")!)
        control.addTarget(self, action: #selector(take_picture_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    /*
    fileprivate lazy var requireDetectedBtn:ST_VerticalButton = {
        
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 9, bottom: 20, right: 9)
        control.title_bottom_offset = 0
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        let attrString = NSMutableAttributedString(string: "要求认证")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 12),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.setTitle(attrString, for: UIControl.State.normal)
        control.setImageForAllStates(ST_ImageUtils.imageName("require_detected_icon")!)
        control.addTarget(self, action: #selector(require_detect_handle), for: UIControl.Event.touchUpInside)
        return control
    }()*/
    
    fileprivate lazy var snap_chat_btn:ST_VerticalButton = {
        
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 9, bottom: 20, right: 9)
        control.title_bottom_offset = 0
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        let attrString = NSMutableAttributedString(string: "阅后即焚")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 12),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.setTitle(attrString, for: UIControl.State.normal)
        control.setImageForAllStates(ST_ImageUtils.imageName("chat_send_snapChat_icon")!)
        control.addTarget(self, action: #selector(send_snap_chat_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var wechat_btn:ST_VerticalButton = {
        
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 9, bottom: 20, right: 9)
        control.title_bottom_offset = 0
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        let attrString = NSMutableAttributedString(string: "微信")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 12),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.setTitle(attrString, for: UIControl.State.normal)
        control.setImageForAllStates(ST_ImageUtils.imageName("chat_send_weChat_icon")!)
        control.addTarget(self, action: #selector(ask_we_chat_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
   
    
    fileprivate lazy var redPacketBtn:ST_VerticalButton = {
        
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 9, bottom: 20, right: 9)
        control.title_bottom_offset = 0
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        let attrString = NSMutableAttributedString(string: "红包")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 12),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.setTitle(attrString, for: UIControl.State.normal)
        control.setImageForAllStates(ST_ImageUtils.imageName("send_chat_redpacket_icon")!)
        control.addTarget(self, action: #selector(send_red_packet_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var media_talk_btn:ST_VerticalButton = {
        
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 9, bottom: 20, right: 9)
        control.title_bottom_offset = 0
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        let attrString = NSMutableAttributedString(string: "通话")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 12),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.setTitle(attrString, for: UIControl.State.normal)
        control.setImageForAllStates(ST_ImageUtils.imageName("send_media_chat_icon")!)
        control.addTarget(self, action: #selector(request_media_talk_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var emoji_talk_btn:ST_VerticalButton = {
        
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 9, bottom: 20, right: 9)
        control.title_bottom_offset = 0
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        let attrString = NSMutableAttributedString(string: "表情")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 12),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.setTitle(attrString, for: UIControl.State.normal)
        control.setImageForAllStates(ST_ImageUtils.imageName("send_emoji_chat_icon")!)
        control.addTarget(self, action: #selector(show_emoji_view), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var gift_talk_btn:ST_VerticalButton = {
        
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 9, bottom: 20, right: 9)
        control.title_bottom_offset = 0
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        let attrString = NSMutableAttributedString(string: "礼物")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 12),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.setTitle(attrString, for: UIControl.State.normal)
        control.setImageForAllStates(ST_ImageUtils.imageName("send_gift_chat_icon")!)
        control.addTarget(self, action: #selector(present_gift_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
//    MARK: -
    //    MARK: - Event
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
       

        if let vc = self.parentViewController as? ST_PrivateChatViewController{
            vc.dismissMessageToolBar()
        }
    }
    
    func setDraft(text:String)  {
        
        self.inputTextView.text = text
        self.inputTextView.textColor = self.input_text_color
        
    }
    
    
    @objc func request_media_talk_handle(){
        
        self.request_media_talk_closure?()
        
    }
    
    @objc func ask_we_chat_handle(){
        
        ask_wechat_closure?()
        
    }
    
    @objc func send_snap_chat_handle(){
        
        if onlyText{
            
            self.parentViewController?.toast(text: "对方开启了不接收图片和视频")
            
            return
        }
        
        if FACE_AVATAE_STATE != 3{
            
            
            self.parentViewController?.toast(text: "请去完成真人头像认证就能使用了哦")
            
            return
        }
        
        guard let vc = TZImagePickerController.init(maxImagesCount: 1, delegate: nil) else{ return }
        
        vc.allowPickingVideo = false
        
        vc.isSelectOriginalPhoto = false
        
        vc.didFinishPickingPhotosHandle = {[weak self] photos,assets,isSelectOriginalPhoto in
            
            
            main_thread_execute {

                guard let img = photos?.first else{
                    return
                }
                
                    self?.picture_images.append(img)
                    
                    self?.heightStatus = .normal
                                            
                    self?.modify_height_status?()
                                            
                    self?.sendImage(img, isSnapChat: true)
                
            }
        }
                    
        GlobalPresent(toController: vc, animated: true)
        
        
        self.heightStatus = .normal
        
        self.modify_height_status?()
        
    }
    
    
    @objc func send_red_packet_handle(){
        
//        let vc = SendRedPacketViewController()
//        
//        vc.send_closure = {[weak self] f ,value in
//            self?.send_red_packet_closure?(f,value)
//        }
//        
//        GlobalPresent(toController: vc)
    }
    
    @objc func require_detect_handle(){
        
        
        if FACE_AVATAE_STATE != 3{
            
            
            self.parentViewController?.toast(text: "请去完成真人头像认证就能使用了哦")
            
            return
        }
        
        self.heightStatus = .normal
        
        inputTextView.resignFirstResponder()
        
        self.modify_height_status?()
        
        self.require_detect_closure?()
    }
    
    @objc func present_gift_handle(){
        
        
        self.heightStatus = .normal
        
        inputTextView.resignFirstResponder()
        
        self.modify_height_status?()
        
        self.present_goods_closure?()
    }
    
    /// 真人未认证 限制
    @objc func face_status_confined_handle(){
        
        ToastDetectFaceTips(vcCreater: nil)
        
    }
    
    
    @objc func select_picture_handle(){
        
        
        if FACE_AVATAE_STATE != 3 && !is_chat_to_assistant {
            
            
            self.parentViewController?.toast(text: "请去完成真人头像认证就能使用了哦")
            
            return
        }
        
        if onlyText{
            
            self.parentViewController?.toast(text: "对方开启了不接收图片和视频")
            
            return
        }
        
        guard let vc = TZImagePickerController.init(maxImagesCount: 1, delegate: nil) else{ return }
        
        
        vc.isSelectOriginalPhoto = false
        
        vc.didFinishPickingPhotosHandle = {[weak self] photos,assets,isSelectOriginalPhoto in
            
            
            main_thread_execute {

                guard let imageArray = photos else{
                    return
                }
                
                for img in imageArray{
                 
                    self?.picture_images.append(img)
                    
                    self?.heightStatus = .normal
                                            
                    self?.modify_height_status?()
                                            
                    self?.sendImage(img)
                    
                }
            }
        }
                    
        vc.didFinishPickingVideoHandle = {[weak self] image , assets in
            
            
            guard let ast = assets , let thumbnailImage = image else { return  }
            
            let options: PHVideoRequestOptions = PHVideoRequestOptions()
               options.version = .original
            
           PHImageManager.default().requestAVAsset(forVideo: ast, options: options, resultHandler: { (asset, audioMix, info) in
            
            main_thread_execute {
                
                if let tempAsset = asset as? AVURLAsset{
                    
                    let videoUrl = tempAsset.url
                    
                    let filename = UUID().uuidString+".mp4"
                    
                    guard var videoPath = SC.push_peculiarity_directory else { return }
                    
                    videoPath.appendPathComponent(filename)
                    
                    do {
                        try FileManager.default.copyItem(at: videoUrl, to: videoPath)
                    } catch (let error) {
                        print("Cannot copy item at \(videoUrl) to \(videoPath): \(error)")
                        return
                    }
                    
                    let size = thumbnailImage.size
                    
                    main_thread_execute {
                        
                        if let thumbnailUrl = self?.save_image_to_document(image: thumbnailImage){
                            
                            self?.heightStatus = .normal
                            
                            self?.modify_height_status?()
                            
                            self?.send_video_closure?(thumbnailUrl.path,size,videoPath.path)
                            
                        }
                    }
                }
                
                
                
            }
               
           })
        }
        GlobalPresent(toController: vc, animated: true)
        
        
        self.heightStatus = .normal
        
        self.modify_height_status?()
        
    }
    
    
    private func sendImage(_ originalImage:UIImage,isSnapChat:Bool = false) {
        
        
        var thumbnailImage:UIImage!
        
        if originalImage.size.width > 280*2{
            
            thumbnailImage = originalImage.resize_image(targetWidth: 280*2)
        }else{
            thumbnailImage = originalImage
        }
        
        
        guard let thumbnialUrl = save_image_to_document(image: thumbnailImage),let imageUrl = save_image_to_document(image: originalImage) else {
            
            self.heightStatus = .normal
            
            self.modify_height_status?()
            
            return
        }
     
        self.send_image_closure?(thumbnialUrl.path,imageUrl.path,thumbnailImage.size, isSnapChat)
        
    }
    
    
    func deal_video_stream(with array:[UIImage])  {
        
        if let asset  = self.last_select_assets.first{
            //                        第一甄
            if   let image = array.first {
                
                var thumbnailImage:UIImage!
                
                if image.size.width > 280*2{
                    thumbnailImage = image.resize_image(targetWidth: 280*2)
                }else{
                    thumbnailImage = image
                }
                
                thumbnailImage = thumbnailImage.fix_orientation()
                
                PHCachingImageManager().requestAVAsset(forVideo: asset, options: nil) { [weak self](avAsset, audio, info) in
                    
                    if let tempAsset = avAsset as? AVURLAsset{
                        
                        let videoUrl = tempAsset.url
                        
                        let filename = UUID().uuidString+".mp4"
                        
                        guard var videoPath = SC.push_peculiarity_directory else { return }
                        
                        videoPath.appendPathComponent(filename)
                        
                        do {
                            try FileManager.default.copyItem(at: videoUrl, to: videoPath)
                        } catch (let error) {
                            print("Cannot copy item at \(videoUrl) to \(videoPath): \(error)")
                            return
                        }
                        
                        let size = thumbnailImage.size
                        
                        main_thread_execute {
                            
                            if let thumbnailUrl = self?.save_image_to_document(image: thumbnailImage){
                                
                                self?.heightStatus = .normal
                                
                                self?.modify_height_status?()
                                
                                self?.send_video_closure?(thumbnailUrl.path,size,videoPath.path)
                                
                            }
                            
                            
                        }
                    }
                }
            }
        }
    }
    

    @objc func take_picture_handle(){
        
        if FACE_AVATAE_STATE != 3{
            
            
            self.parentViewController?.toast(text: "请去完成真人头像认证就能使用了哦")
            
            return
        }
        
        if onlyText{
            
            self.parentViewController?.toast(text: "对方开启了不接收图片和视频")
            
            return
        }
        
        let vc = ST_RGCameraController()
        
        vc.completeActionBlock = { url, type in

//            DTLocalStrorage.setData(key: DTLocalStrorage.alreadySelectedImageKey, value: JSON(true))
            
            if type == .video {
               
                self.saveMovie(mediaStr: url)
            }//如果是图片
            else if type == .image{
                if let originalImage = UIImage.init(contentsOfFile: url){
                    
                    print("BUG拍图-originalImage.size:",originalImage.size)
                    
                    let thumbnailImage = originalImage.resize_image(targetWidth: 140)
                    
                    //                originalImage.scaled(toWidth: 140)
                    guard let thumbnailUrl = self.save_image_to_document(image: thumbnailImage) else{
                        
                        self.heightStatus = .normal
                        
                        self.modify_height_status?()
                        
                        return
                    }
                    
                    self.heightStatus = .normal
                    
                    self.modify_height_status?()
                    
                    self.send_image_closure?(thumbnailUrl.path,url,thumbnailImage.size, false)
                    
                }else{
                    
//                    DTLocalStrorage.setData(key: DTLocalStrorage.alreadySelectedImageKey, value: JSON(false))
                }
            }
            
        }
 
        vc.modalPresentationStyle = .fullScreen
        
        self.parentViewController?.present(vc, animated: true, completion: nil)
     
    }
    
    
    private func save_image_to_document(image:UIImage)->URL?{
        // get the documents directory url
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        // choose a name for your image
        let fileName = UUID().uuidString
        // create the destination file url to save your image
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        // get your UIImage jpeg data representation and check if the destination file url already exists
        if let data = image.jpegData(compressionQuality:  1.0),
            !FileManager.default.fileExists(atPath: fileURL.path) {
            do {
                // writes the image data to disk
                try data.write(to: fileURL)
//                print("FILE--URL-2:",fileURL)
                return fileURL
            } catch {
                
                print("saveImageToDocument -- error saving file: \(error)")
                
                return nil
            }
        }
        
        return nil
    }
    
    
    @objc func audio_record_hanlde(sender:UIButton){
        
        if is_chat_to_assistant {
            return
        }
        
        if self.heightStatus != .speaker {
        
            self.heightStatus = .speaker
            
            inputTextView.resignFirstResponder()
        
           
            
            self.modify_height_status?()
            
        }else{
           
            self.heightStatus = .normal
            
            inputTextView.becomeFirstResponder()
            
            self.modify_height_status?()
        }
        
    }
    
    @objc fileprivate func send_text_handle(){
        
        
        self.send_text_closure?(inputTextView.text)
        self.inputTextView.text = ""
    }
    
    @objc func show_emoji_view(){
        
        
        if self.vc?.judgementSendMsgOperation() == false{
            return
        }
        
        print("【showEmoji---】 上一次的模式",self.heightStatus)
        
        
        
        if self.input_status_control_btn.isSelected {
            self.input_status_control_btn.isSelected = false
            self.heightStatus = .keybroad
            inputTextView.inputView = nil
            inputTextView.returnKeyType = .send
            inputTextView.reloadInputViews()
            change_to_input_text_control.removeFromSuperview()
//            inputTextView.becomeFirstResponder()
        }else{
            self.heightStatus = .face
            self.input_status_control_btn.isSelected = true
            self.inputTextView.inputView = self.emojiView
            inputTextView.reloadInputViews()
            
            
            self.addSubview(change_to_input_text_control)
            
//            change_to_input_text_control.backgroundColor = .random
            
            change_to_input_text_control.snp.makeConstraints { (make) in
                make.edges.equalTo(inputTextView)
            }
        }
        
        self.inputTextView.becomeFirstResponder()
        
        
       self.modify_height_status?()
        
    }
    @objc func show_operation_view(){
        
        if self.vc?.judgementSendMsgOperation() == false{
            return
        }
        
        if self.heightStatus == .selectPicture {
            return
        }
        
        self.inputTextView.resignFirstResponder()
    
        self.heightStatus = .selectPicture
        
        self.modify_height_status?()
    }
    
    
}
//MARK: - UIImagePickerControllerDelegate
extension ST_BTChatInputBar:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// Local variable inserted by Swift 4.2 migrator.
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)

        
//        if DTLocalStrorage.getData(key: DTLocalStrorage.alreadySelectedImageKey).boolValue{
//
//            return
//        }
        
        picker.dismiss(animated: true, completion: nil)
        
        
//        DTLocalStrorage.setData(key: DTLocalStrorage.alreadySelectedImageKey, value: JSON(true))
        
        //info是一个字典，包含了拍摄结果的各种信息
        let infodic:NSDictionary = info as NSDictionary
        
        //获取键值UIImagePickerControllerMediaType的值，表示了当前处理的是视频还是图片
        let mediaType = infodic["UIImagePickerControllerMediaType"] as! String
        
        //如果是视频的话
        if mediaType == kUTTypeMovie as String{
//            saveMovie(infodic: infodic)
        }
            //如果是图片
        else if mediaType == kUTTypeImage as String{
            if let originalImage = self.originalImage(info){
                
                print("BUG拍图-originalImage.size:",originalImage.size)
                
//                let thumbnailImage = originalImage.resize_image(targetWidth: 140)
                
                //                originalImage.scaled(toWidth: 140)
                self.heightStatus = .normal
                self.modify_height_status?()
                
            }else{
//                DTLocalStrorage.setData(key: DTLocalStrorage.alreadySelectedImageKey, value: JSON(false))
            }
        }
    }
//    func fix_orientation(img:UIImage) -> UIImage {
//         let rect = CGRect(x: 0, y: 0, width: img.size.height, height: img.size.width)
//        UIGraphicsBeginImageContextWithOptions(rect.size, false, img.scale)
//
//        img.draw(in: rect)
//
//        let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()!
//        UIGraphicsEndImageContext()
//
//        return normalizedImage
//    }
    //保存视频方法
    func saveMovie(mediaStr:String){
        //系统保存到tmp目录里的视频文件的路径
        
             let mediaUrl = URL.init(fileURLWithPath: mediaStr)
            if let image = mediaUrl.thumbnail(){
                
                var thumbnailImage:UIImage!
                
//                【重点】录制的库 有问题 需要 旋转 90度
                if image.size.height > 280*2{
                    thumbnailImage = image.resize_image(targetHeight: 280*2)
                }else{
                    thumbnailImage = image
                }
                
                thumbnailImage = thumbnailImage.rotated(by: .pi/2.0)

                    main_thread_execute {
                        
                        self.heightStatus = .normal
                        self.modify_height_status?()
                        
                        
                        if let thumbnailUrl =  self.save_image_to_document(image: thumbnailImage){
                            
                            self.send_video_closure?(thumbnailUrl.path,thumbnailImage.size,mediaStr)
                            
                        }
                    }
            }

    }
  
    
    func originalImage(_ info: [String : Any]) -> UIImage? {
//        return info[UIImagePickerControllerOriginalImage] as? UIImage
        if let image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage{
            
            return image.fix_orientation()
            
        }
        
        return nil
    }
    
}

/*
extension ST_BTChatInputBar:EmojiViewDelegate{
    
    func emojiViewDidPressSendButton(_ emojiView: EmojiView) {
        
        guard self.inputTextView.text.count > 0 else {
            return
        }
        self.send_text_closure?(inputTextView.text)
        inputTextView.text = ""
    }
    
    
    
    func emojiViewDidSelectEmoji(_ emoji: String, emojiView: EmojiView) {
        
        inputTextView.insertText(emoji)
    }
    
    func emojiViewDidPressChangeKeyboardButton(_ emojiView: EmojiView) {
        inputTextView.inputView = nil
        inputTextView.returnKeyType = .send
        inputTextView.reloadInputViews()
    }
    
    func emojiViewDidPressDeleteBackwardButton(_ emojiView: EmojiView) {
        inputTextView.deleteBackward()
    }
    
    func emojiViewDidPressDismissKeyboardButton(_ emojiView: EmojiView) {
        inputTextView.resignFirstResponder()
    }
    
}
*/

extension ST_BTChatInputBar:UITextViewDelegate{
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        
        if textView.textColor == input_placeholder_text_color {
            textView.text = nil
            textView.textColor = input_text_color
        }
    }
    
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        
        if self.vc?.judgementSendMsgOperation() == false{
            return false
        }
        
        return true
    }
    
    
    func textViewDidEndEditing(_ textView: UITextView) {
        
        if textView.text.isEmpty {
            textView.text = input_placeholder_text
            textView.textColor = input_placeholder_text_color
        }
    }
    
    
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        if text == "\n" {
            self.send_text_closure?(textView.text)
            textView.text = ""
            return false
        }
        return true
    }
    
}
